package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;


public class RefreshTokenInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;
    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*
        *
        * 使用Session进行校验
            HttpSession session = request.getSession();
            User user1 = (User) session.getAttribute("user");
            if(user1==null){
                response.setStatus(401);
                return false;
            }
            UserDTO user = new UserDTO();
            user.setId(user1.getId());
            user.setIcon(user1.getIcon());
            user.setNickName(user1.getNickName());
            UserHolder.saveUser(user);
        *
        * */
        /**
         *     @Override
         *     public boolean isEmpty() {
         *         return value.length == 0;
         *     }
         * */
        String authorization = request.getHeader("authorization");
        if (authorization == null || authorization.isEmpty()) {
            return true;
        }
        String key = RedisConstants.LOGIN_USER_KEY + authorization;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
//        userMap==null 这个不需要写的原因 userMap.isEmpty() 时会抛出 NullPointerException。所以你可以简化为：
        if (userMap.isEmpty()) {
            response.setStatus(401);
            return false;
        }
        // 解析以及储存
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        UserHolder.saveUser(userDTO);
        /*
         *   刷新token的有效期
         *   为什么要刷新呢？
         *      这个位置主要是说 当我设置有效期为30min 但是这个用户准备完40分钟 不能说我在他玩的时候给他退了
         *      所以 按照用户最后一次上线之后的30分钟为 有效期是体验感最好的
         * */
        stringRedisTemplate.expire(key,RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
